package net.expectx.pay.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.expectx.common.single.base.BaseResultConstants;
import net.expectx.common.single.util.formatter.MessageFormatter;
import net.expectx.pay.common.AdminConstants;
import net.expectx.pay.common.AdminResult;
import net.expectx.pay.common.BaseController;
import net.expectx.pay.dao.bean.MerchantUser;
import net.expectx.pay.dao.bean.PermissionUser;
import net.expectx.pay.rpc.api.PermissionUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 单点登录管理
 *
 * @author jianhun
 * @date 2018/5/17
 */
@Controller
@RequestMapping("/sso")
@Api(value = "单点登录管理", description = "单点登录管理")
public class SsoController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(SsoController.class);
    /**
     * code key
     */



    @Autowired
    PermissionUserService permissionUserService;


    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {
        LOGGER.info(MessageFormatter.format("-----------------------{}-------------------------------", "进入登录"));
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        PermissionUser permissionUser = (PermissionUser) session.getAttribute("permissionUser");
        if (null!=permissionUser) {
            String backUrl = request.getParameter("backurl");
            if (StringUtils.isBlank(backUrl)) {
                backUrl = "/";
            } else {
            }
            StringBuffer sb = new StringBuffer("redirect:").append(backUrl);
            return sb.toString();
        }
        return "login";


    }

    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");
        String vercode = request.getParameter("vercode");

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        PermissionUser permissionUser = (PermissionUser)  session.getAttribute("permissionUser");
        if (null==permissionUser) {
            if (vercode.toLowerCase().equals(session.getAttribute("KAPTCHA_SESSION_KEY").toString().toLowerCase())){
                // 使用shiro认证
                UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
                try {
                    if (StringUtils.isNotEmpty(rememberMe)) {
                        usernamePasswordToken.setRememberMe(true);
                    } else {
                        usernamePasswordToken.setRememberMe(false);
                    }
                    subject.login(usernamePasswordToken);
                } catch (UnknownAccountException e) {
                    return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "帐号不存在！",null);
                } catch (IncorrectCredentialsException e) {
                    return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "密码错误！",null);
                } catch (LockedAccountException e) {
                    return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "帐号已锁定！",null);
                }
            }else{
                return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "验证码错误！",null);
            }
        }

        // 回跳登录前地址
        String backurl = request.getParameter("backurl");
        if (StringUtils.isBlank(backurl)) {
        }

        return new AdminResult(Boolean.TRUE,BaseResultConstants.SUCCESS, backurl);
    }



    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {

        /**
         * shiro退出登录
         */
        SecurityUtils.getSubject().logout();
        /**
         * 跳回原地址
         */
        String redirectUrl = request.getHeader("Referer");
        if (null == redirectUrl) {
            redirectUrl = "/";
        }

        StringBuffer sb = new StringBuffer("redirect:").append(redirectUrl);
        return sb.toString();

    }

}
